from rest_framework.exceptions import APIException
from rest_framework import status
from django.utils.translation import gettext_lazy as _

class BaseException(APIException):
    """
    基础异常类
    """
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = _('发生错误')
    default_code = 'error'

    def __init__(self, detail=None, code=None):
        if detail is None:
            detail = self.default_detail
        if code is None:
            code = self.default_code
            
        self.detail = str(detail)
        self.code = code
class ValidationError(BaseException):
    """验证错误"""
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = _('数据验证失败')
    default_code = 'validation_error'

class AuthenticationError(BaseException):
    """认证错误"""
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = _('认证失败')
    default_code = 'authentication_error'

class PermissionError(BaseException):
    """权限错误"""
    status_code = status.HTTP_403_FORBIDDEN
    default_detail = _('权限不足')
    default_code = 'permission_denied'

class NotFoundError(BaseException):
    """资源不存在"""
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = _('资源不存在')
    default_code = 'not_found'

class BusinessError(BaseException):
    """业务错误"""
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = _('业务处理失败')
    default_code = 'business_error'

class SystemError(BaseException):
    """系统错误"""
    status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    default_detail = _('系统错误')
    default_code = 'system_error'

def custom_exception_handler(exc, context):
    """
    自定义异常处理
    """
    from rest_framework.views import exception_handler
    from rest_framework.response import Response
    
    # 先调用REST framework默认的异常处理
    response = exception_handler(exc, context)
    
    if response is not None:
        # 获取原始的错误信息
        detail = response.data.get('detail', str(response.data))
        code = getattr(exc, 'default_code', response.status_code)
        
        # 统一响应格式
        response.data = {
            'code': code,
            'message': str(detail),
            'data': None
        }
    
    return response 
